/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tradeplus.security;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.tradeplus.security.model.User;
import com.tradeplus.security.service.UserDetailsService;

/**
 *
 * @author ronnie
 */
public class BTPAuthenticationProvider implements AuthenticationProvider {
	
	private UserDetailsService userDetailsService;
	
    public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}

	@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();
		User user = null;
		user = retrieveUser(username, (BTPAuthenticationToken) authentication);
		Authentication returnAuthentication = createSuccessAuthentication((BTPAuthenticationToken) authentication, user);
		
		return returnAuthentication;
    }

    @Override
    public boolean supports(Class authentication) {
        return (BTPAuthenticationToken.class.isAssignableFrom(authentication));
    }
    
    protected Authentication createSuccessAuthentication(BTPAuthenticationToken token, User user) {
    	BTPAuthenticationToken result = new BTPAuthenticationToken(user.getAuthorities(), token.getUsername(), 
    			token.getPassword(), token.getSite(), token.getDomain(), user.getId());
    	result.setDetails(token.getDetails());
    	
    	return result;
    }
    
    public User retrieveUser(String username, BTPAuthenticationToken authentication) throws AuthenticationException {
    	User user = userDetailsService.loadDBUser(authentication.getUsername(), authentication.getPassword(), authentication.getSite(), 
    			authentication.getDomain());
    	
    	return user;
    }
}
